package br.com.treinamento.gestaoExperienciaProfissional.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.treinamento.gestaoExperienciaProfissional.model.Usuario;

@WebFilter(urlPatterns = "/paginas/*")
public class LoginFilter implements Filter {

	private static final String URL_LOGIN = "login.jsf";

	public void init(FilterConfig arg0) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		HttpSession session = httpServletRequest.getSession();
		Usuario usuario = (Usuario) session.getAttribute("usuario");

		if (usuario == null) {
			String urlLogin = getLoginUrl(httpServletRequest);
			HttpServletResponse httpServletResponse = ((HttpServletResponse) response);
			httpServletResponse.sendRedirect(urlLogin);
		} else {
			chain.doFilter(request, response);
		}
	}

	public void destroy() {
	}

	public String getLoginUrl(HttpServletRequest httpServletRequest) {
		return String.format("%s/%s", httpServletRequest.getContextPath(), URL_LOGIN);
	}

}
